const express = require('express');
const pool = require('../utils/pool')
let router = express.Router();
router.get('/FuzzySearch',(req,res)=>{
	var obj= req.query


	let sql = 'select * from product'
	let params = []
	let conditions = []
  	// 处理name参数
	if(obj.name && obj.name.trim() !== '') {
		conditions.push('name LIKE ?')
		params.push(`%${obj.name}%`)
	}
	
	// 处理shopName参数
	if(obj.className && obj.className.trim() !== '') {
		conditions.push('className LIKE ?')
		params.push(`%${obj.className}%`)
	}
	

	
	// 如果有查询条件，添加到SQL语句中
	if(conditions.length > 0) {
		sql += ' where ' + conditions.join(' and ')
	}
	
	pool.query(sql, params, (x,y)=>{
		if(x){
			throw x
		}
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
	})
})
router.get('/allSearch',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('select*from product',(x,y)=>{
		if(x){
			throw x
		}
		// console.log(y);
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
		
	})
	
})
router.get('/classSearch',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('select*from product where code = ?',[obj.code],(x,y)=>{
		if(x){
			throw x
		}
		console.log(x);
    console.log(y);
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
		
	})
	
})
router.get('/classNameSearch',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('select*from product where className = ?',[obj.className],(x,y)=>{
		if(x){
			throw x
		}
		console.log(x);
    console.log(y);
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
		
	})
	
})
router.get('/idSearch',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('select*from product where id = ?',[obj.id],(x,y)=>{
		if(x){
			throw x
		}
		console.log(x);
    console.log(y);
		if(y.length===0){
			res.send({code:400,msg:'查询错误'})
		}else{
			res.send({code:200,msg:'查询成功' ,data:y})
		}
		
	})
	
})
router.post('/productAdd',(req,res)=>{
  let obj = req.body
  console.log(obj);
	pool.query('insert into product set ?',[obj],(x,y)=>{
		if(x){
			throw x;
		}
		console.log(y);
		res.send({code:200,msg:'注册成功'})
	})
 
});
router.get('/productDelete',(req,res)=>{
	var obj= req.query
	console.log(obj);
	pool.query('delete from product where id = ? ',[obj.id],(x,y)=>{
		if(x){
			throw x
		}
		console.log(y);
		if(y.affectedRows===0){
			res.send({code:400,msg:'不存在'})
		}else{
			res.send({code:200,msg:'删除成功'})
		}
		
	})
	
})
router.post('/productUpdate',(req,res)=>{
	var obj = req.body
	console.log(obj);
	pool.query('update product set  ? where id = ?',[obj,obj.id],(x,y)=>{
		if(x){
			throw x
		}
		console.log(y);
		if(y.affectedRows===0){
			res.send({code:400,msg:'修改失败'})
		}else{
			res.send({code:200,msg:'修改成功',date:obj})
		}
		
	})
	
})

module.exports=router;